package org.ewicom.ppsaddressbook.model;

import java.util.ArrayList;
import java.util.List;

import org.ewicom.ppsaddressbook.DatabaseHelper;
import org.ewicom.ppsaddressbook.PPSAddressBook.PhoneColumns;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class PhoneDataSource {

	private SQLiteDatabase db;
	private DatabaseHelper dbHelper;

	private static final String[] PHONE_PROJECTION = new String[] {
			PhoneColumns._ID, PhoneColumns.TYPE, PhoneColumns.PHONE, };

	private static final int COLUMN_INDEX_PHONE_ID = 0;
	private static final int COLUMN_INDEX_PHONE_TYPE = 1;
	private static final int COLUMN_INDEX_PHONE_PHONE = 2;

	public PhoneDataSource(Context context) {
		dbHelper = new DatabaseHelper(context);
	}

	public void open() throws SQLException {
		db = dbHelper.getReadableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public List<Phone> getAllPhones() {
		List<Phone> phones = new ArrayList<Phone>();

		Cursor cursor = db.query(PhoneColumns.PHONE_TABLE_NAME,
				PHONE_PROJECTION, null, null, null, null,
				PhoneColumns.DEFAULT_SORT_ORDER);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Phone phone = CursorToPhone(cursor);
			phones.add(phone);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return phones;
	}

	public List<Phone> getPhonesByUnitId(long unitId) {
		List<Phone> phones = new ArrayList<Phone>();

		Cursor cursor = db.query(PhoneColumns.PHONE_TABLE_NAME,
				PHONE_PROJECTION,
				PhoneColumns.UNIT_ID + "=" + String.valueOf(unitId), null,
				null, null, PhoneColumns.DEFAULT_SORT_ORDER);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Phone phone = CursorToPhone(cursor);
			phones.add(phone);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return phones;
	}

	private Phone CursorToPhone(Cursor cursor) {
		Phone phone = new Phone();

		phone.setId(cursor.getLong(COLUMN_INDEX_PHONE_ID));
		phone.setType(cursor.getString(COLUMN_INDEX_PHONE_TYPE));
		phone.setPhone(cursor.getString(COLUMN_INDEX_PHONE_PHONE));

		return phone;
	}

}
